<template>
    <el-dialog :title="dialogTitle" :visible.sync="formDialogVisible"
               custom-class='dialog_right dialogScroll_add sell-ticket-form' top="0%"
               @close='closeDialog' @open="openDialog">
      <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">

        <div class="ticket-card">
          <el-row class="station-info">
            <el-col :span="8" class="station-name">{{ orderDetail.startSite }}</el-col>
            <el-col :span="8">
              <div class="detail-info">
                约{{ orderDetail.time }}小时
                <mk-ticket-arrow class="ticket-arrow"></mk-ticket-arrow>
              </div>
            </el-col>
            <el-col :span="8" class="station-name">{{ orderDetail.endSite }}</el-col>
          </el-row>
          <div class="other-info">
            <el-row :gutter="20">
              <el-col :span="4">发车时间</el-col>
              <el-col :span="20">{{ orderDetail.rideTime | formatMinutes}}</el-col>
            </el-row>
            <el-row :gutter="20" v-if="handleType==='stepTwo'">
              <el-col :span="4">车票数量</el-col>
              <el-col :span="20">{{ orderDetail.count }} 张</el-col>
            </el-row>
            <el-row :gutter="20" v-if="handleType==='stepTwo'">
              <el-col :span="4">座位号</el-col>
              <el-col :span="20">
                <span v-for="(item,index) in orderDetail.seatNumbers" :key="index">
                  <span v-if="index != 0">、</span>{{ item }}
                </span>
              </el-col>
            </el-row>
          </div>
        </div>

        <el-form :model="submitForm" :rules="submitFormRules"
                 ref="submitForm" label-width="96px">
          <template v-if="handleType==='stepOne'">
            <el-form-item label="购票人姓名" prop="buyer">
              <el-input v-model="submitForm.buyer"
                        placeholder="请输入购票人姓名（必填）"></el-input>
            </el-form-item>

            <el-form-item label="电话" prop="phone">
              <el-input v-model="submitForm.phone"
                        placeholder="请输入电话（必填）"></el-input>
            </el-form-item>

            <el-form-item label="购票数量" prop="count" class="form-item-height">
              <el-input-number v-model="submitForm.count"
                               :min="1" :max="maxTicketCount"></el-input-number>
            </el-form-item>

            <el-form-item label="应收金额">
              ￥{{ orderDetail.price | currency('', 2) }} * {{ submitForm.count }}
            </el-form-item>

            <el-form-item label="合计金额" style="border-bottom: 1px solid #f0f3f6;padding-bottom: 12px;">
              ￥{{(orderDetail.price * submitForm.count) | currency('', 2) }}
            </el-form-item>

            <el-form-item label="支付方式" prop="payWay">
              <el-radio-group v-model="submitForm.payWay">
                <el-radio label="XianJin">现金</el-radio>
                <el-radio label="ShuaKa">刷卡</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <div class="el-form-item-info" v-if="handleType==='stepTwo'">
            <el-form-item label="购票人姓名">{{ orderDetail.buyer }}</el-form-item>
            <el-form-item label="电话">{{ orderDetail.phone }}</el-form-item>
            <el-form-item label="单价">￥{{ orderDetail.price | currency('', 2) }}</el-form-item>
            <el-form-item label="合计金额">￥{{ orderDetail.totalPrice | currency('', 2) }}</el-form-item>
            <el-form-item label="支付方式">{{ orderDetail.payWayCN}}</el-form-item>
          </div>
        </el-form>
      </el-scrollbar>

      <div slot="footer" class="dialog-footer footerStyle">
        <template v-if="handleType==='stepOne'">
          <!--<mk-permission :perms="['Ticket:TicketManagement:SellTicket:create']"> 列表中权限以判断-->
            <el-button type="primary" class="btn-primary" :disabled="isSubmitLoading"
                       @click='submitSell'>去结算</el-button>
          <!--</mk-permission>-->
          <el-button type='primary' class='btn-cancel' :disabled="isSubmitLoading"
                     @click="formDialogVisible = false">取消</el-button>
        </template>

        <template v-if="handleType==='stepTwo'">
          <mk-permission :perms="['Ticket:TicketManagement:SellTicket:print']">
            <a class="print-btn" target="_blank"
               :href="'/order/print.pdf?id=' + orderDetail.id"
               @click="submitPrint">确定并打印</a>
          </mk-permission>
          <el-button type='primary' class='btn-cancel' :disabled="isSubmitLoading"
                     @click="formDialogVisible = false">取消</el-button>
        </template>
      </div>
    </el-dialog>
</template>

<script>
  import MkTicketArrow from '../../../components/ticketArrow.vue'
  import ticketService from '../../../services/ticket'
  import MkPermission from "../../../components/MkPermission"
  import {mapState} from 'vuex'
  export default {
    name: 'sellTicketForm',

    components: {
      MkTicketArrow, MkPermission
    },
    computed: mapState({
      bodyHeight: state=> state.global.bodyHeight,
    }),
    props: ['dialogVisible', 'currentRow'],

    methods: {
      closeDialog() {
        this.$refs.submitForm.resetFields();
        this.$emit('closeDialog');
      },
      openDialog() {
        this.dialogTitle = '购票';
        this.handleType = 'stepOne';
        this.orderDetail = this.currentRow;
        this.maxTicketCount = this.orderDetail.remainTicket;
      },

      submitSell () {
        this.$refs['submitForm'].validate((valid) => {
          if (valid) {
            this.isSubmitLoading = true;
            this.submitForm.id = this.orderDetail.scheduleRecordId;
            this.submitForm.midWayId = this.orderDetail.midWayId;
            ticketService.sellTicketServer (this.submitForm, data => {
              this.$refs.submitForm.resetFields();
              this.isSubmitLoading = false;
              this.handleType = 'stepTwo';
              this.dialogTitle = '信息确认';
              this.orderDetail = data.data;
            }, data => {
              this.isSubmitLoading = false;
            });
          }
        });
      },

      submitPrint () {
        this.$emit('submitSuccess');
        this.$emit('closeDialog');
      }
    },

    watch: {
      dialogVisible: function (value) {
        this.formDialogVisible = value;
      }
    },

    mounted () {
    },
    data () {
      let checkPhone = (rule, value, callback) => {
        value = (value + '').trim();
        if (value) {
          if (/^1(3|4|5|7|8)\d{9}$/.test(value)) {
            callback();
          } else {
            callback(new Error('请输入正确的手机号'));
          }
        } else {
          callback(new Error('请输入手机号'));
        }
      };
      let checkCount = (rule, value, callback) => {
        value = (value + '').trim();
        if (value) {
          if (this.$utils.isNumber(value) && value.indexOf('.') > -1) {
            callback(new Error('请输入整数'));
          } else {
            callback();
          }
        } else {
          callback(new Error('请选择购票数量'));
        }
      };
      let checkName = (rule, value, callback) => {
        let reg = new RegExp("[`~!@#$%^&*()_=+|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】《》‘；：”“'。，、？-]");
        let regFont = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (value) {
          if (reg.test(value) || /[0-9]/.test(value) || !regFont.test(value)) {
            callback(new Error('请输入正确的姓名'));
          } else {
            callback();
          }
        } else {
          callback(new Error('请输入姓名'));
        }
      };

      return {
        dialogTitle: '购票',
        isSubmitLoading: false,
        formDialogVisible: false,
        handleType: 'stepOne',
        orderDetail: {
          time: '',
          startSite: '',
          endSite: '',
          rideTime: ''
        },
        maxTicketCount: 50,
        submitForm: {
          buyer: '',
          count: '',
          id: '',
          midWayId: '',
          payWay: '',
          phone: ''
        },
        submitFormRules: {
          buyer: { validator: checkName },
          count: { validator: checkCount },
          payWay: { required: true, message: '请选择支付方式', trigger: 'change' },
          phone:  { validator: checkPhone, trigger: 'blur' },
        },
      }
    },

    filters: {
      formatMinutes (value) {
        if (value) {
          return new Date(value).pattern('yyyy-MM-dd HH:mm');
        } else {
          return '';
        }
      }
    }
  }
</script>

<style lang='less'>
  @import "../../../assets/style/main";

  .sell-ticket-form {
    .el-form-item-info {
      .el-form-item {
        margin-bottom: 0px;
      }
    }
    .ticket-card {
      margin-bottom: 40px;
      width: 84%;
    }
    .form-item-height {
      .el-form-item__content {
        height: 36px;
      }
    }
    .print-btn {
      background-color: @primaryColor;
      text-decoration: none;
      color: #fff;
      font-size: 14px;
      height: 36px;
      line-height: 36px;
      display: inline-block;
      .my-border-radius(4px);
      padding: 0 20px;
      margin-right: 10px;
      &:hover {
        .my-opacity(0.8);
      }
    }
    .ticket-card {
      padding: 30px;
      background-color: @borderColor;
      .station-info .el-col {
        width: auto;
        max-width: 33.3333%;
      }
      .station-name {
        padding-top: 10px;
        font-size: 24px;
        color: @fontColorOne;
      }
      .detail-info {
        min-width: 122px;
        text-align: center;
        position: relative;
        line-height: 28px;
        font-size: 14px;
        color: @fontColorTwo;
      }
      .ticket-arrow {
        position: absolute;
        left: 10px;
        top: 20px;
      }
      .other-info {
        padding-top: 30px;
        .el-row + .el-row {
          padding-top: 10px;
        }
        .el-col:first-child {
          text-align: right;
        }
        .el-col:last-child {
          color: @fontColorOne;
        }
      }
    }
  }

</style>
